#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
记录模块相关路由
"""

import logging
import json
from flask import Blueprint, request, jsonify
from base.services.record_service import RecordService

logger = logging.getLogger(__name__)

# 创建蓝图
record_bp = Blueprint('record', __name__)

@record_bp.route('/services', methods=['POST'])
def create_record_service():
    """创建记录服务"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取服务信息
        service_name = data.get('service_name')
        service_ip = data.get('service_ip')
        service_port = data.get('service_port')

        if not service_name:
            return jsonify({"error": "服务名称不能为空"}), 400

        # 创建记录服务
        service_id = RecordService.create_record_service(service_name, service_ip, service_port)

        # 获取创建的服务详情
        service = RecordService.get_record_service_by_id(service_id)

        return jsonify(service), 201

    except Exception as e:
        logger.error(f"创建记录服务失败: {e}")
        return jsonify({"error": f"创建记录服务失败: {str(e)}"}), 500

@record_bp.route('/services', methods=['GET'])
def get_record_services():
    """获取记录服务列表"""
    try:
        # 获取分页参数
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 10))

        # 获取记录服务列表
        result = RecordService.get_record_services(page, page_size)

        return jsonify(result), 200

    except Exception as e:
        logger.error(f"获取记录服务列表失败: {e}")
        return jsonify({"error": f"获取记录服务列表失败: {str(e)}"}), 500

@record_bp.route('/services/<service_id>', methods=['GET'])
def get_record_service(service_id):
    """获取记录服务详情"""
    try:
        # 获取记录服务详情
        service = RecordService.get_record_service_by_id(service_id)

        if not service:
            return jsonify({"error": "记录服务不存在"}), 404

        return jsonify(service), 200

    except Exception as e:
        logger.error(f"获取记录服务详情失败: {e}")
        return jsonify({"error": f"获取记录服务详情失败: {str(e)}"}), 500

@record_bp.route('/services/<service_id>', methods=['PUT'])
def update_record_service(service_id):
    """更新记录服务"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取服务信息
        service_name = data.get('service_name')
        service_ip = data.get('service_ip')
        service_port = data.get('service_port')
        is_active = data.get('is_active')

        # 更新记录服务
        success = RecordService.update_record_service(
            service_id, service_name, service_ip, service_port, is_active
        )

        if not success:
            return jsonify({"error": "记录服务不存在"}), 404

        # 获取更新后的服务详情
        service = RecordService.get_record_service_by_id(service_id)

        return jsonify(service), 200

    except Exception as e:
        logger.error(f"更新记录服务失败: {e}")
        return jsonify({"error": f"更新记录服务失败: {str(e)}"}), 500

@record_bp.route('/services/<service_id>', methods=['DELETE'])
def delete_record_service(service_id):
    """删除记录服务"""
    try:
        # 删除记录服务
        success = RecordService.delete_record_service(service_id)

        if not success:
            return jsonify({"error": "记录服务不存在"}), 404

        return jsonify({"message": "记录服务删除成功"}), 200

    except Exception as e:
        logger.error(f"删除记录服务失败: {e}")
        return jsonify({"error": f"删除记录服务失败: {str(e)}"}), 500

@record_bp.route('/requests', methods=['POST'])
def create_request_record():
    """创建请求记录"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取请求记录信息
        service_id = data.get('service_id')
        client_service_name = data.get('client_service_name')
        server_service_name = data.get('server_service_name')
        request_method = data.get('request_method')
        request_url = data.get('request_url')
        request_headers = data.get('request_headers', {})
        request_body = data.get('request_body')
        response_status = data.get('response_status')
        response_headers = data.get('response_headers', {})
        response_body = data.get('response_body')

        # 验证必填字段
        if not service_id:
            return jsonify({"error": "服务ID不能为空"}), 400
        if not server_service_name:
            return jsonify({"error": "服务端服务名称不能为空"}), 400
        if not request_method:
            return jsonify({"error": "请求方法不能为空"}), 400
        if not request_url:
            return jsonify({"error": "请求URL不能为空"}), 400

        # 创建请求记录
        record_id = RecordService.create_request_record(
            service_id, client_service_name, server_service_name,
            request_method, request_url, request_headers, request_body,
            response_status, response_headers, response_body
        )

        # 获取创建的请求记录详情
        record = RecordService.get_request_record_by_id(record_id)

        return jsonify(record), 201

    except Exception as e:
        logger.error(f"创建请求记录失败: {e}")
        return jsonify({"error": f"创建请求记录失败: {str(e)}"}), 500

@record_bp.route('/requests', methods=['GET'])
def get_request_records():
    """获取请求记录列表"""
    try:
        # 获取查询参数
        service_id = request.args.get('service_id')
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 10))

        # 获取请求记录列表
        result = RecordService.get_request_records(service_id, page, page_size)

        return jsonify(result), 200

    except Exception as e:
        logger.error(f"获取请求记录列表失败: {e}")
        return jsonify({"error": f"获取请求记录列表失败: {str(e)}"}), 500

@record_bp.route('/requests/<record_id>', methods=['GET'])
def get_request_record(record_id):
    """获取请求记录详情"""
    try:
        # 获取请求记录详情
        record = RecordService.get_request_record_by_id(record_id)

        if not record:
            return jsonify({"error": "请求记录不存在"}), 404

        return jsonify(record), 200

    except Exception as e:
        logger.error(f"获取请求记录详情失败: {e}")
        return jsonify({"error": f"获取请求记录详情失败: {str(e)}"}), 500

@record_bp.route('/requests/<record_id>', methods=['DELETE'])
def delete_request_record(record_id):
    """删除请求记录"""
    try:
        # 删除请求记录
        success = RecordService.delete_request_record(record_id)

        if not success:
            return jsonify({"error": "请求记录不存在"}), 404

        return jsonify({"message": "请求记录删除成功"}), 200

    except Exception as e:
        logger.error(f"删除请求记录失败: {e}")
        return jsonify({"error": f"删除请求记录失败: {str(e)}"}), 500

@record_bp.route('/requests/<record_id>/convert', methods=['GET'])
def convert_to_request_definition(record_id):
    """将请求记录转换为请求定义"""
    try:
        # 将请求记录转换为请求定义
        request_definition = RecordService.convert_to_request_definition(record_id)

        if not request_definition:
            return jsonify({"error": "请求记录不存在"}), 404

        return jsonify(request_definition), 200

    except Exception as e:
        logger.error(f"将请求记录转换为请求定义失败: {e}")
        return jsonify({"error": f"将请求记录转换为请求定义失败: {str(e)}"}), 500

@record_bp.route('/start', methods=['POST'])
def start_recording():
    """开始记录"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取服务ID列表
        service_ids = data.get('service_ids', [])
        if not service_ids:
            return jsonify({"error": "服务ID列表不能为空"}), 400

        # 获取网络接口
        interface = data.get('interface', 'eth0')

        # 调用拦截组件的捕获服务
        import requests
        import os

        # 使用环境变量或默认值获取拦截组件的服务地址
        intercept_host = os.getenv('INTERCEPT_HOST', 'kube-relayer-intercept')
        intercept_port = os.getenv('INTERCEPT_PORT', '5555')

        logger.info(f"尝试连接拦截组件: http://{intercept_host}:{intercept_port}/api/intercept_control/capture/start")

        response = requests.post(
            f'http://{intercept_host}:{intercept_port}/api/intercept_control/capture/start',
            json={
                'interface': interface,
                'service_ids': service_ids
            }
        )

        if response.status_code != 200:
            return jsonify({"error": f"启动捕获服务失败: {response.text}"}), 500

        # 返回结果
        return jsonify(response.json()), 200

    except Exception as e:
        logger.error(f"开始记录失败: {e}")
        return jsonify({"error": f"开始记录失败: {str(e)}"}), 500

@record_bp.route('/stop', methods=['POST'])
def stop_recording():
    """停止记录"""
    try:
        # 调用拦截组件的捕获服务
        import requests
        import os

        # 使用环境变量或默认值获取拦截组件的服务地址
        intercept_host = os.getenv('INTERCEPT_HOST', 'kube-relayer-intercept')
        intercept_port = os.getenv('INTERCEPT_PORT', '5555')

        logger.info(f"尝试连接拦截组件: http://{intercept_host}:{intercept_port}/api/intercept_control/capture/stop")

        response = requests.post(f'http://{intercept_host}:{intercept_port}/api/intercept_control/capture/stop')

        if response.status_code != 200:
            return jsonify({"error": f"停止捕获服务失败: {response.text}"}), 500

        # 返回结果
        return jsonify(response.json()), 200

    except Exception as e:
        logger.error(f"停止记录失败: {e}")
        return jsonify({"error": f"停止记录失败: {str(e)}"}), 500

@record_bp.route('/status', methods=['GET'])
def get_recording_status():
    """获取记录状态"""
    try:
        # 调用拦截组件的捕获服务
        import requests
        import os

        # 使用环境变量或默认值获取拦截组件的服务地址
        intercept_host = os.getenv('INTERCEPT_HOST', 'kube-relayer-intercept')
        intercept_port = os.getenv('INTERCEPT_PORT', '5555')

        logger.info(f"尝试连接拦截组件: http://{intercept_host}:{intercept_port}/api/intercept_control/capture/status")

        response = requests.get(f'http://{intercept_host}:{intercept_port}/api/intercept_control/capture/status')

        if response.status_code != 200:
            return jsonify({"error": f"获取捕获服务状态失败: {response.text}"}), 500

        # 返回结果
        return jsonify(response.json()), 200

    except Exception as e:
        logger.error(f"获取记录状态失败: {e}")
        return jsonify({"error": f"获取记录状态失败: {str(e)}"}), 500
